package com.yuyou.fn.common.util;

import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created by lzh on 2019/2/18.
 */
public class TmsPaySignUtils {
    public static String getSignStr(Map<String, String> params) {

        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        String prestr = "";

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            //跳过sign参数
            if("sign".equalsIgnoreCase(key)){
                continue;
            }
            String value = params.get(key);

            if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }

        return prestr;
    }

    public static String sign(Map<String, String> params, String key) {
        String signStr = getSignStr(params);
        signStr = signStr+key;
        try {
            return DigestUtils.md5DigestAsHex(signStr.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            return null ;
        }
    }
}
